<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card>
        <!-- 添加角色按钮 -->
        <el-row>
            <el-col>
                <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
            </el-col>
        </el-row>
        <!-- 角色列表区域 -->
        <el-table :data="roselist" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
                <template slot-scope="scope">
                    <el-row :class="['bdbottom','vcenter',i1===0?'bdtop':'']" v-for="(i,i1) in scope.row.children" :key="i.id">
                        <!-- 渲染一级权限 -->
                        <el-col :span="5">
                            <el-tag  closable @close="removeRightById(scope.row,i.id)">{{i.authName}}</el-tag>
                            <i class="el-icon-caret-right"></i>
                        </el-col>
                        <!-- 渲染二级 三级权限 -->
                        <el-col :span="19">
                            <!-- 通过for循环渲染二级权限 -->
                            <el-row :class="[i2 === 0 ? '' : 'bdtop','vcenter']" v-for="(e, i2) in i.children" :key="e.id">
                                <el-col :span="6">
                                    <el-tag  closable @close="removeRightById(scope.row,e.id)" type="success">{{e.authName}}</el-tag>
                                    <i class="el-icon-caret-right"></i>
                                </el-col>
                                <el-col :span="18">
                                    <el-tag 
                                    closable
                                    @close="removeRightById(scope.row,t.id)"
                                    type="warning" 
                                    v-for="(t,i3) in e.children" 
                                    :key="t.id"
                                    :class="[i3 === 0 ? '' : 'bdtop']">
                                    {{t.authName}}</el-tag>
                                </el-col>
                            </el-row>
                        </el-col>
                    </el-row>
                </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index"></el-table-column>
            <el-table-column prop="roleName" label="角色名称"></el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
            <el-table-column label="操作" width="300px">
                <!-- eslint-disable-next-line -->
                <template slot-scope="scope">
                    <el-button size="mini" type="primary" icon="el-icon-edit" @click="edit_Role(scope.row.id)">编辑</el-button>
                    <el-button size="mini" type="danger" icon="el-icon-delete" @click="delete_role(scope.row.id)">删除</el-button>
                    <el-button size="mini" type="warning" icon="el-icon-setting" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                </template>
            </el-table-column>
        </el-table>    
    </el-card>
    <!-- 分配权限弹框 -->
    <el-dialog
        title="分配权限"
        :visible.sync="setRightDiglogVisible"
        width="50%" @colse="setRightClose">
        <!-- 树形控件 -->
        <el-tree :data="rightslist" :props="treeProps" show-checkbox node-key="id"   default-expand-all :default-checked-keys="defKeys" ref="treeRef"></el-tree>
        <span slot="footer" class="dialog-footer">
            <el-button @click="setRightDiglogVisible = false">取 消</el-button>
            <el-button type="primary" @click="allotRights">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 添加角色谈话框 -->
    <el-dialog
        title="添加角色"
        :visible.sync="addDialogVisible"
        width="50%" @close="addClose">
        <el-form :model="addRuleForm" :rules="addRules" ref="addruleForm" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="addRuleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="addRuleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addRoles">确 定</el-button>
        </span>
    </el-dialog>
    <!-- 编辑角色功能 -->
    <el-dialog
        title="编辑"
        :visible.sync="editDialogVisible"
        width="50%">
        <el-form :model="editRuleForm" :rules="addRules" ref="editRuleForm" label-width="100px">
            <el-form-item label="角色名称" prop="roleName">
                <el-input v-model="editRuleForm.roleName"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="roleDesc">
                <el-input v-model="editRuleForm.roleDesc"></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editRoles">确 定</el-button>
        </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
    name:'Roles',
    data() {
        return {
            roselist:[],
            setRightDiglogVisible:false,
            // 所有权限的数据
            rightslist:[],
            // 树形控件的属性绑定
            treeProps:{
                label: 'authName',
                children: 'children'
            },
            //默认选中的节点 id值数组
            defKeys:[],
            // 当前即将分配权限的角色id
            roleId:'',
            // 控制分配角色谈话框显示与隐藏
            addDialogVisible:false,
            // 分配角色谈话框表单的数据对象
            addRuleForm:{
                roleName:'',
                roleDesc:''
            },
            // 分配角色谈话框表单的验证规则
            addRules:{
               roleName:[
                   { required: true, message: '请输入角色名称', trigger: 'blur' },
                   { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'blur' }
               ],
               roleDesc:[
                   { required: true, message: '请输入角色描述', trigger: 'blur' },
                   { min: 2, max: 12, message: '长度在 2 到 12 个字符', trigger: 'blur' }
               ]
            },
            // 编辑角色功能
            editDialogVisible:false,
            // 编辑角色表单数据
            editRuleForm:{},
        }
    },

    created() {
        // 获取所有角色的列表
        this.getRoseList()
    },
    methods: {
        // 获取所有角色的列表
        async getRoseList(){
            const {data:res} = await this.$http.get('roles')
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('角色列表获取失败')
            this.roselist=res.data
            console.log(this.roselist);
        },
        // 删除三级权限功能
        async removeRightById(role,rightId){
            //弹框确定是否要删除
            const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(err=>err)
            console.log(confirmResult);
            //如果确定 则返回字符串 confirm
            //如果取消 则返回字符串 cancel
            if(confirmResult !== 'confirm') return this.$message.error('删除权限失败！')
            this.$message.success('删除权限成功！')
            const {data:res} = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('删除权限失败！');
            role.children = res.data
        },
        //分配权限功能
        async showSetRightDialog(role){
            this.roleId = role.id
            // 获取所有权限的数据
            const {data: res} = await this.$http.get('rights/tree')
            console.log(res);
            if(res.meta.status !== 200) return this.$message.error('分配权限失败！')
            // 把获取到的所有权限数据保存到 rightslist 数组中
            this.rightslist = res.data
            // 调用递归找到角色拥有权限的三级节点的id值  并保存到 defKeys 数组中
            this.getLeafKeys(role,this.defKeys)
            // console.log(this.defKeys);
            this.setRightDiglogVisible = true
        },
        //通过递归的形式 获取角色下的 三级权限的id
        getLeafKeys(node,arr){
            // 如果是三级节点，则没有children属性，为假，取反为真进入if判断，在数组arr中追加该节点id
            if(!node.children) {
                return arr.push(node.id)
            }
            node.children.forEach(item => this.getLeafKeys(item,arr));
            // console.log(arr);
        },
        //监听分配 对话框的 关闭事件
        setRightClose(){
            //关闭分配权限谈话框时 将 defKeys 清空 防止出现 defKeys数组中的 id值越来越多
            this.defKeys=[]
        },
        //点击分配角色 谈话框的确定按钮 发起post请求 为当前角色分配角色 
        async allotRights(){
            const keys = [
                ...this.$refs.treeRef.getCheckedKeys(),
                ...this.$refs.treeRef.getHalfCheckedKeys()
            ]
            const idStr = keys.join(',')
            const {data: res} = await this.$http.post(`roles/${this.roleId}/rights`,{rids: idStr})
            if(res.meta.status !== 200) return this.$message.error('为当前角色分配权限失败！')
            this.$message.success('分配权限成功！')
            this.getRoseList()
            // console.log(res);
            this.setRightDiglogVisible = false
        },
        // 添加角色按钮的点击事件
        addRoles(){
            //表单预验证
            this.$refs.addruleForm.validate(async valid=>{
                // console.log(valid); //如果添加了新的角色则返回 true
                if(!valid) return 
                const {data:res} = await this.$http.post('roles',this.addRuleForm)
                console.log(res)
                if(res.meta.status !== 201) return this.$message.error('添加角色失败！')
                this.$message.success('添加角色成功！')
                this.getRoseList()     
                this.addDialogVisible=false
            })
           
        },
        // 添加完新角色，将表单内容清空
        addClose(){
            //1.清空表单数数据对象
            // this.addRuleForm={}
            // 2.
            this.$refs.addruleForm.resetFields()
        },
        // 删除角色功能
        async delete_role(id){
           const confirmId = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
            confirmButtonText: '确定', cancelButtonText: '取消',type: 'warning'}).catch(err=>err)
            //如果确认删除 则返回 字符串 confirm
            //如果取消删除 则返回 字符串 cancel
            // console.log(confirmId);
            if(confirmId!=='confirm') return this.$message.info('已取消删除！')
            const {data: res} = await this.$http.delete('roles/'+id)
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.eroor('删除角色失败！')
            this.$message.success('删除角色成功！')
            this.getRoseList()
        },
        // 点击编辑 打开谈话框
        async edit_Role(id){
            const {data: res} = await this.$http.get('roles/'+id)
            // console.log(res);
            if(res.meta.status !== 200) return this.$message.error('获取角色数据失败!')
            this.editRuleForm=res.data
            console.log(this.editRuleForm);
            this.editDialogVisible = true
        },
        // 编辑角色功能 点击确定
        editRoles(){
            this.$refs.editRuleForm.validate(async valid=>{
                // console.log(valid);
                if(!valid) return
               const {data: res} = await this.$http.put('roles/'+this.editRuleForm.roleId,{
                    roleName: this.editRuleForm.roleName,
                    roleDesc: this.editRuleForm.roleDesc,})
                console.log(res);               
                if(res.meta.status !== 200) return this.$message.error('修改角色数据失败!')
                this.$message.success('修改角色数据成功!')
                this.getRoseList()
                this.editDialogVisible = false
            })
        }
    },
}
</script>

<style scoped>
    .el-tag{
        margin: 7px;
    }
    .bdtop{
        border-top: 1px solid #eee;
    }
    .bdbottom{
        border-bottom: 1px solid #eee;
    }
    .vcenter{
        display: flex;
        align-items: center;
    }
</style>